﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebHoiChoMuaBan.Models;

namespace WebHoiChoMuaBan.Controllers.Helpers
{
    public class PhotoHelper : HelperBase
    {
        public struct FetchPhotoResult
        {
            public List<Photo> photos;
            public int totalPages;
        }

        public PhotoHelper(): base()
        {

        }

        private List<Photo> CreateListNews(int page, int rowPerPage, IEnumerable<Photo> photo)
        {
            List<Photo> pagedPhoto = photo.Skip((page - 1) * rowPerPage).Take(rowPerPage).ToList();

            int totalPages = (int)Math.Ceiling((double)photo.Count() / rowPerPage);

            List<Photo> lstPhoto = new List<Photo>(totalPages);
            foreach (var item in pagedPhoto)
            {
                lstPhoto.Add(item);
            }
            return lstPhoto;
        }

        private FetchPhotoResult CreateFetchNews(int page, int rowPerPage, IEnumerable<Photo> newNews)
        {
            List<Photo> pagedNewMemers = newNews.Skip((page - 1) * rowPerPage).Take(rowPerPage).ToList();

            int totalPages = (int)Math.Ceiling((double)newNews.Count() / rowPerPage);

            List<Photo> lstNews = new List<Photo>(totalPages);
            foreach (var item in pagedNewMemers)
            {
                lstNews.Add(item);
            }
            FetchPhotoResult result;
            result.totalPages = totalPages;
            result.photos = lstNews;
            return result;
        }

        public FetchPhotoResult getAllPhotos(int pageNum, int itemPerPage)
        {
            IEnumerable<Photo> photo = null;
            photo = from n in this.dataContext.Photos
                    orderby n.PhotoId descending
                    select n;
            return CreateFetchNews(pageNum, itemPerPage, photo);
        }

        public Photo GetPhotoById(int photoId)
        {
            return this.dataContext.Photos.SingleOrDefault(n => n.PhotoId == photoId);
        }

        public List<Photo> LoadAllPhotosOfAlbum(int albumID)
        {
            var news = (from n in this.dataContext.Photos
                        where n.AlbumId == albumID
                        select n);
            return news.ToList();
        }

        public void Add(Photo photo)
        {
            this.dataContext.Photos.InsertOnSubmit(photo);
        }

        //Delete Methods
        public void Delete(Photo photo)
        {
            this.dataContext.Photos.DeleteOnSubmit(photo);
        }

        public void Save()
        {
            this.dataContext.SubmitChanges();
        }
    }
}
